<?php

// start session
session_start();

function check_sport($sport, $username, $conn) {

    $query = 'SELECT * FROM availability WHERE username = \'' . $username . '\' AND sport = \'' . $sport . '\'';
    $result = pg_query($conn, $query);
    $row = pg_fetch_row($result);
    if (pg_num_rows($result) == 0) {
        echo "rows returned" . pg_num_rows($result);
        return False;
    }
    return True;
}

// connect to database
$conn_str = 'host=dbsrv1.cdf.toronto.edu dbname=csc309g23 user=csc309g23 password=ipheid5h';
$conn = pg_connect($conn_str);
$sports_query = 'SELECT * FROM sports';
$sports = pg_query($conn, $sports_query);
while ($sport = pg_fetch_row($sports)) {
    if (($_POST[$sport[0]] == NULL) && (check_sport($sport[0], $_SESSION['username'], $conn))) {
        $remove_query = 'DELETE FROM availability WHERE username =\'' . $_SESSION['username'] . '\' AND sport =\'' . $sport[0] . '\'';
        $rem_result = pg_query($conn, $remove_query);
    } else if (($_POST[$sport[0]] == $sport[0]) && (!(check_sport($sport[0], $_SESSION['username'], $conn)))) {
        $add_query = 'INSERT INTO availability (username, sport) VALUES (\'' . $_SESSION['username'] . '\',\'' . $sport[0] . '\')';
        $add_result = pg_query($conn, $add_query);
    }
}
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>